<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px" size="mini">
      <el-row :gutter="15">
        <div class="orderNo">调拨单号：{{ form.wareAllocateOdd }}</div>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="调出仓库" prop="wareOutId">
            <treeselect v-model="form.wareOutId" :normalizer="normalizer" :options="wareOutOptions"
                        placeholder="请选择"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="调出人" prop="wareOutPerson">
            <el-select v-model="form.wareOutPerson" filterable placeholder="请选择">
              <el-option v-for="item in wareOutPersonOptions" :key="item.userId" :label="item.nickName"
                         :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="调入仓库" prop="wareInId">
            <treeselect v-model="form.wareInId" :normalizer="normalizer" :options="wareInOptions" placeholder="请选择"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="调入人" prop="wareInPerson">
            <el-select v-model="form.wareInPerson" filterable placeholder="请选择">
              <el-option v-for="item in wareInPersonOptions" :key="item.userId" :label="item.nickName"
                         :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="调拨时间" prop="wareAllocateDate">
            <el-date-picker v-model="form.wareAllocateDate" clearable placeholder="请选择" type="datetime"
            format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button :disabled="!form.wareOutId" icon="el-icon-plus" plain size="mini" type="primary"
                     @click="handleAddCommodity">添加商品
          </el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-table v-loading="loading" :data="form.detailsList" border>
          <el-table-column align="center" label="商品类别" prop="commodityType"/>
          <el-table-column align="center" label="商品编号" prop="commodityNo"/>
          <el-table-column align="center" label="商品名称" prop="commodityName1"/>
          <el-table-column align="center" label="规格" prop="commoditySpec"/>
          <el-table-column align="center" label="调拨单位" prop="unitName1">
            <template slot-scope="scope">
              <el-select v-model="scope.row.commodityUnitId" placeholder="请选择" @change="handleTableRowSelectChange($event, scope.row)">
                <el-option v-for="item in scope.row.unitList" :key="item.commodityUnitId" :label="item.unitName1" :value="item.commodityUnitId"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="单位关系" prop="unitResult"/>
          <el-table-column align="center" label="换算结果" prop="unitRelationship"/>
          <el-table-column align="center" label="当前库存" prop="wareCommodityNumber"/>
          <el-table-column align="center" label="调拨数量" prop="wareAllocateNumber">
            <template slot-scope="scope">
              <el-input v-model="scope.row.wareAllocateNumber"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
            <template slot-scope="scope">
              <el-button v-hasPermi="['erp:ErpSupplierCommodity:remove']" icon="el-icon-delete" size="mini" type="text" @click="handleDeleteCommodity(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" :autosize="{ minRows: 4, maxRows: 4 }" placeholder="请输入"
                      type="textarea"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer-options">
      <el-button type="primary" @click="submitForm(-1)">保存草稿</el-button>
      <el-button type="primary" @click="submitForm(0)">提交审核</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!-- 选择商品 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isCommodityOpen" append-to-body title="选择商品"
               width="80%">
      <ErpCommodity v-if="isCommodityOpen" :notCommodityIds="notCommodityIds" :wareId="form.wareOutId"
                    @SelectionChange="handleSelectionChange">
      </ErpCommodity>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectedCommdity">确 定</el-button>
        <el-button @click="isCommodityOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {addErpWareAllocate, getErpWareAllocate, updateErpWareAllocate} from "@/api/erp/ErpWareAllocate";
import {getSysUserList} from '@/api/system/user'
import {listErpWareHouse} from "@/api/erp/ErpWareHouse";
import ErpCommodity from '@/views/erp/ErpCommodity/selectedCommodity'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: {
    ErpCommodity,
    Treeselect
  },
  props: [],
  data() {
    return {
      // 调出仓库
      wareOutOptions: [],
      // 调出人
      wareOutPersonOptions: [],
      // 调入仓库
      wareInOptions: [],
      // 调入人
      wareInPersonOptions: [],
      // 选择商品页面
      isCommodityOpen: false,
      form: {},
      rules: {
        wareOutId: [
          {required: true, message: "调出仓库不能为空", trigger: "blur"}
        ],
        wareOutPerson: [
          {required: true, message: "调出人不能为空", trigger: "blur"}
        ],
        wareInId: [
          {required: true, message: "调入仓库不能为空", trigger: "blur"}
        ],
        wareInPerson: [
          {required: true, message: "调入人不能为空", trigger: "blur"}
        ],
        wareAllocateDate: [
          {required: true, message: "调拨时间不能为空", trigger: "blur"}
        ],
      },
    }
  },
  created() {
    this.reset();
    this.handleGetListSysUser();
    this.getTreeselect();
    const wareAllocateId = this.$route.params && this.$route.params.wareAllocateId;
    if (wareAllocateId != 0) {
      this.getWareAllocateInfo(wareAllocateId);
    } else {
      this.loading = false;
    }
  },
  mounted() {

  },
  methods: {
    // 获取详情
    getWareAllocateInfo(id) {
      getErpWareAllocate(id).then(response => {
        this.form = response.data;
      });
    },
    // 获取用户列表
    handleGetListSysUser() {
      getSysUserList().then(res => {
        this.wareInPersonOptions = res.data;
        this.wareOutPersonOptions = res.data;
      })
    },
    /** 转换仓库管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.wareId,
        label: node.wareName,
        children: node.children
      };
    },
    /** 查询仓库管理下拉树结构 */
    getTreeselect() {
      listErpWareHouse().then(response => {
        this.wareOutOptions = this.handleTree(response.data, "wareId", "warePid");
        this.wareInOptions = this.wareOutOptions;
      });
    },
    // 仓库选择
    handleTreeSelectNode(e) {
      this.wareId = e.wareId;
    },
    // 选择商品
    handleAddCommodity() {
      // 设置商品过滤id
      this.notCommodityIds = this.form.detailsList?.map(item => item.commodityId);
      this.isCommodityOpen = true;
    },
     // 商品单位选择
     handleTableRowSelectChange(e, row) {
      let obj = row.unitList.find(item => {
        return item.commodityUnitId == e
      })
      row.unitResult = obj.unitResult;
      row.unitRelationship = obj.unitRelationship;
      row.commodityUnitId = obj.commodityUnitId;
    },
    /** 提交按钮 */
    submitForm(approveStatus) {
      if(this.form.detailsList.length == 0){
        return this.$message.error('请选择调拨商品！');;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.approveStatus = approveStatus;
          if (this.form.wareAllocateId != null) {
            updateErpWareAllocate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              const obj = {path: "/psi/stock/ErpWareAllocate", name: "ErpWareAllocate"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          } else {
            addErpWareAllocate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              const obj = {path: "/psi/stock/ErpWareAllocate", name: "ErpWareAllocate"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          }
        }
      });
    },
    // 取消
    cancel() {
      const obj = {path: "/psi/stock/ErpWareAllocate", name: "ErpWareAllocate"};
      this.$tab.closeOpenPage(obj);
      this.$tab.refreshPage(obj);
    },
    // 商品选择
    handleSelectionChange(selection) {
      this.temporyList = selection;
    },
    // 确定选择商品
    submitSelectedCommdity() {
      this.temporyList.forEach((item) => {
        this.form.detailsList.push({
          ...item
        });
      });
      this.isCommodityOpen = false;
    },
    /** 删除商品 */
    handleDeleteCommodity(row) {
      const index = this.form.detailsList.indexOf(row);
      if (index > -1) {
        this.form.detailsList.splice(index, 1);
      }
    },
    // 表单重置
    reset() {
      this.form = {
        wareAllocateOdd: 'DB' + this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}'),
        wareOutId: null,
        wareOutPerson: null,
        wareInId: null,
        wareInPerson: null,
        wareAllocateDate: this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
        remark: null,
        createId: null,
        createName: null,
        createTime: null,
        flag: null,
        approveStatus: null,
        approveId: null,
        approveName: null,
        approveTime: null,
        rejectTime: null,
        rejectReason: null,
        detailsList: []
      };
      this.resetForm("form");
    },
  }
}

</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

::v-deep .el-table__cell{
  padding: 0px;
}
</style>
